package com.novax.ex.activity.provider.controller.inner;


import com.novax.ex.activity.infrastructure.entity.IeoConfig;
import com.novax.ex.activity.infrastructure.entity.IeoOrder;
import com.novax.ex.activity.infrastructure.entity.IeoStages;
import com.novax.ex.activity.open.api.inner.IeoStagesDistributionTaskApi;
import com.novax.ex.activity.provider.service.IeoConfigService;
import com.novax.ex.activity.provider.service.IeoOrderService;
import com.novax.ex.activity.provider.service.IeoStagesService;
import com.novax.ex.common.core.redis.RedisDistributedLocker;
import com.novax.ex.common.core.redis.RedisLockUtil;
import com.novax.ex.common.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import jakarta.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * @Description: 定时任务
 * @Author: ChenXi
 * @Date:  2023/5/6 10:32
 **/
@Slf4j
@RestController
public class IeoStagesDistributionTaskController implements IeoStagesDistributionTaskApi {

    @Resource
    private IeoConfigService ieoConfigService;

    @Resource
    private IeoOrderService ieoOrderService;

    @Resource
    private IeoStagesService ieoStagesService;

    @Resource
    private RedisDistributedLocker redisLocker;

    @Resource
    private ExecutorService executorService;

    @Override
    public void ieoStageDistribution() {
        log.info("ieo 分期发币 ->");
        // 查询所有应发币的分期IEO配置
        List<IeoConfig> stageIeoConfigs = ieoConfigService.findAllStageIeo();
        if(stageIeoConfigs.isEmpty()){
            log.info("ScheduleTask stageIeoConfig isEmpty");
            return;
        }

        Date now = new Date();
        // 当前时间
        String nowStr = DateUtil.dateTo10String(now);

        // 分布式锁 防止定时任务重复处理
        String ieoTaskLockKey = RedisLockUtil.IEO_TASK_LOCK;
        boolean ieoLock = redisLocker.tryLock(ieoTaskLockKey, false);
        try {
            if(ieoLock){
                // 所有应发币的IEO配置
                for (IeoConfig ieoConfig : stageIeoConfigs) {
                    // ieoId
                    Long ieoId = ieoConfig.getId();

                    boolean last = false;
                    // 查询解锁时间在now之前的分期配置
                    List<IeoStages> ieoStagesList = ieoStagesService.findByIeoId(ieoId, now);
                    // 最后一期ID
                    Long lastIdByIeoId = ieoStagesService.findLastIdByIeoId(ieoId);
                    if(!ieoStagesList.isEmpty()){
                        for (IeoStages ieoStages : ieoStagesList) {
                            // 已发过直接跳过
                            Integer ieoStagesState = ieoStages.getState();
                            if(ieoStagesState == 1){
                                log.info("ScheduleTask stages ieoStageDistribution 此分期已发过, stageId:{}, ieoId:{}", ieoStages.getId(), ieoStages.getIeoId());
                                continue;
                            }
                            Date unlockTime = ieoStages.getUnlockTime();
                            // 判断是否已到时间 时间准确到小时
                            if(nowStr.equals(DateUtil.dateTo10String(unlockTime))){
                                // 是否最后一期
                                last = lastIdByIeoId.equals(ieoStages.getId());

                                // 真实分配总份数
                                Integer sharePortion = ieoConfig.getSharePortion();
                                Integer state = ieoConfig.getState();
                                Integer unfreeze = ieoConfig.getUnfreeze();

                                // 如果活动未开启或者没有开启发币则不处理
                                if(state == 0 || unfreeze != 3){
                                    log.info("ScheduleTask stages Unfree 活动未开启或者已经解冻过, ieoId:{}, unfreeze:{}", ieoId, unfreeze);
                                    continue;
                                }

                                // 分配总数为0 不做处理
                                if(sharePortion.equals(0)){
                                    log.info("ScheduleTask stages equals 0 sharePortion:{},", sharePortion);
                                    continue;
                                }

                                // 所有订单
                                List<IeoOrder> allIeoOrderList = ieoOrderService.selectOrderByIeoId(ieoId);
                                if(allIeoOrderList.isEmpty()){
                                    log.info("ScheduleTask stages unfree 订单为空, ieoId:{}", ieoId);
                                    continue;
                                }

                                // 分期发币
                                executorService.execute(() -> {
                                    ieoOrderService.stagesUnfree(ieoStages, allIeoOrderList, now, false);
                                });

                                // 发完币更新状态
                                ieoStages.setState(1);
                                ieoStagesService.modifySelective(ieoStages);
                            } else {
                                continue;
                            }
                        }
                        // 如果处理了最后一期
                        if(last){
                            ieoConfig.setUnfreeze(4);
                            ieoConfigService.modifySelective(ieoConfig);
                        }
                    }
                }
            }

        } catch (Exception e) {
            log.error("------------------IEO task 定时任务分期处理error", e);
        } finally {
            //  解锁
            redisLocker.unlock(ieoTaskLockKey);
        }

    }
}
